package com.lyc.ssm.action;

import com.lyc.ssm.domain.Student;
import com.lyc.ssm.domain.Teacher;
import com.lyc.ssm.domain.User;
import com.lyc.ssm.service.IStudentService;
import com.lyc.ssm.service.ITeacherService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

@Controller
@RequestMapping("demo")//设置请求映射地址
public class DemoAction {

    @Autowired
    private IStudentService studentService;

    //使用字符串
    //  /demo/test
    @RequestMapping("/test")
    public String test() {

        System.out.println("饕餮 双击666 中文不乱码");
        System.out.println("JRebel Done");
        return "test";//会返回视图解析器解析后获得的路径的视图
    }

    //使用模型视图
    //  /demo/test
    @RequestMapping(value = "/modelAndView")
    public ModelAndView modelAndView() {
        ModelAndView mav = new ModelAndView();
        mav.addObject("id", 711);
        mav.addObject("name", "lyc");
        mav.setViewName("test");//设置视图名称
        return mav;
    }

    //获取参数，注意请求地址
    // /demo/get/711/lyc
    @RequestMapping(value = "/get/{id}/{name}", method = RequestMethod.GET)//只接受GET请求
    public String get(ModelMap map, @PathVariable Integer id, @PathVariable String name) {//获取GET请求参数
        map.addAttribute("id", id);//保存数据至页面
        map.addAttribute("name", name);
        return "test";
    }

    //获取POST请求参数
    // /demo/post
    @RequestMapping(value = "/post", method = RequestMethod.POST)//只接受POST请求
    public String post(ModelMap map, User user) {//将POST请求参数封装至user对象中
        map.addAttribute("user", user);
        return "test";
    }

    //上述操作默认都是请求转发
    //重定向至/demo/yooLin请求地址对应的视图
    // /demo/redirect
    @RequestMapping(value = "/redirect")
    public String post() {//将POST请求参数封装至user对象中
        return "redirect:/demo/yooLin";
    }
    // /demo/yooLin
    @RequestMapping("/yooLin")
    public String yooLin() {
        return "yooLin";
    }

    //操作request
    // /demo/request
    @RequestMapping("/request")
    public String request(HttpServletRequest request) {
        request.setAttribute("id", 711);
        request.setAttribute("name", "lyc");
        return "test";
    }

    //获取json数据封装至user对象
    // /demo/getJson
    @RequestMapping(value = "/json2Object",method = RequestMethod.POST)
    public String json2Object(@RequestBody User user,ModelMap map){//@RequestBody会根据消息转换器将json数据转换成user对象
        System.out.println(user);
        map.addAttribute("user",user);
        return "test";
    }

    //发送user对象解析后的json数据
    // /demo/sendJson
    @RequestMapping("/object2Json")
    @ResponseBody//会根据消息转换器将返回值解析成json数据并响应
    public User object2Json(){
        User user = new User();
        user.setId(711);
        user.setName("lyc");
        return user;
    }

    //上传文件
    // /demo/upload
    @RequestMapping("/upload")
    public String upload(MultipartFile file, HttpServletRequest request) {
        try {
            //获得表单中的name属性值
            String fn = new String(file.getName().getBytes("iso8859-1"), "utf-8");
            System.out.println(fn);
            //获得文件名
            String fileName = new String(file.getOriginalFilename().getBytes("iso8859-1"), "utf-8");
            System.out.println(fileName);
            //获取文件类型
            String fileType = file.getContentType();
            System.out.println(fileType);
            //获取WEB-INF目录
            File f = new File(request.getServletContext().getRealPath("/WEB-INF/upload"), fileName);
            //WEB-INF不存在则创建该目录
            if (!f.exists() && !f.isDirectory()) {
                f.mkdir();
            }
            //将上传的文件保存至指定路径下
            file.transferTo(f);
            System.out.println("文件上传成功");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "test";
    }

    //使用响应头完成文件下载操作
    // /demo/download
    @RequestMapping("/download")
    public ResponseEntity<byte[]> download(HttpServletRequest request) {
        try {
            File file = new File(request.getServletContext().getRealPath("/WEB-INF/upload") + "/IMG_20170714_083513.jpg");
            if (!file.exists()) {
                System.out.println("文件不存在");
                return null;
            }
            //创建响应头
            HttpHeaders headers = new HttpHeaders();
            //添加附件并设置其名称
            headers.setContentDispositionFormData("attachment", file.getName());
            //设置附件格式
            headers.setContentType(MediaType.IMAGE_JPEG);
            //返回响应体
            //FileUtils.readFileToByteArray(file) 将文件读取成字节数组
            //HttpStatus.CREATED 设置新建状态，表示文件下载
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping("/addStudent")
    public String addStudent(@RequestBody Student student){
        studentService.addStudent(student);
        return "test";
    }

    @RequestMapping("/addStudentAndTeacher")
    public String addStudentAndTeacher(@RequestBody Student student){
        Teacher teacher = new Teacher();
        teacher.setName("shixi");
        studentService.addStudentWithTeacher(student,teacher);
        return "test";
    }
}
